package com.reagent.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: JWT工具类
 * @ClassNmae: JWTUtils
 * @Author: HeYue
 * @DateTime: 2020-11-23 02:15
 **/
@Slf4j
public class JWTUtils {

    //注意：在真正的开发中SING是很复杂的，这里只做演示
    private static final String SING = "!Q@W#E$R";

    /*
     * 生成Token  header.payload.sing
     */
    public static String generateToken(Map<String, String> withClaims) {
        //创建Map集合
        HashMap<String, Object> map = new HashMap<>();
        //创建日历
        Calendar instance = Calendar.getInstance();
        //设置过期时间(这里设置7天过期)
        instance.add(Calendar.SECOND, 60 * 60);
        //创建JWT
        JWTCreator.Builder builder = JWT.create();
        //添加存放信息
        withClaims.forEach(builder::withClaim);
        String token = builder.withExpiresAt(instance.getTime())//指定令牌过期时间
                .sign(Algorithm.HMAC256(SING)); //设置签名(指定密钥方式)
        return token;
    }

    /*
     * 验证Token  header.payload.sing
     */
    public static DecodedJWT verifyToken(String token) {
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
        return verify;
    }

    /*
     * 获取当前Token
     */
    public static String getCurrentToken() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("token");
        return token;
    }


}